const Service = require('egg').Service;

// const mock = require('mockjs')
// const { list } = mock.mock({
//     'list|4-6': [{
//         name:'@cname',
//         tel:/^1[3-9]\d{9}$/,
//         title: '@ctitle',
//         'news|40-500':1,
//         'two|15-200':1,
//         'send|10-300':1,
//         'state|1':['在职','离职'],
//     }]
// })

class HomeService extends Service {
    async getPeo() {
        const { ctx, app } = this

        // list.forEach(item => {
        //     this.app.mysql.insert('peoples', item)
        // })

        const { id, keyword, pageIndex, pageSize } = ctx.query;
        let sql = `select * from peoples where 1=1 `
        let sqlCount = `select count(id) as total from peoples where 1=1 `
        if (id) {
            sql += `and id=${id} `
            sqlCount += `and id=${id} `
        }
        if (keyword) {
            sql += `and title like "%${keyword}%" `
            sqlCount += `and title like "%${keyword}%" `
        }
        if (pageIndex && pageSize) {
            sql += `limit ${(pageIndex - 1) * pageSize},${pageSize} `
        }
        const data = await app.mysql.query(sql)
        const [{ total }] = await app.mysql.query(sqlCount)
        return {
            total,
            data
        }
    }

    /// 添加经纪人数据
    async addPeo() {
        const { ctx, app } = this
        const data = await app.mysql.insert('peoples', { ...ctx.request.body })
        return data
    }

    /// 编辑经纪人数据
    async editPeo() {
        const { ctx, app } = this
        const { id } = ctx.request.body
        const data = await this.app.mysql.update('peoples', { ...ctx.request.body, id })
        return data
    }

    /// 删除经纪人数据
    async delPeo() {
        const { ctx, app } = this
        const data = await app.mysql.delete('peoples', { id: ctx.params.id })
        return data
    }

    /// 判断经纪人数据
    async switchBroker() {
        const { ctx, app } = this
        const { type } = ctx.query;
        const data = await this.app.mysql.select('peoples', { // 搜索 post 表
            where: { state: type }, // WHERE 条件
        })
        return data
    }

}

module.exports = HomeService;